# == Coding: UTF-8 ==
# @Project :        DormitoryManagementSystem
# @fileName         forget_password.py  
# @version          v0.5
# @author           Echo
# @GiteeWarehouse   https://gitee.com/liu-long068/
# @editsession      2023/6/1
# @Software:        PyCharm
# ====/******/=====
import hashlib
import json
import random
import time

from public.utils.login import Login


class ForgetPassword:
    def __init__(self):
        self.users = []
        self.path = r'D:\BooksManagementSystem\public\users\student.json'
        self.load_users()  # 加载所有用户信息

    def load_users(self):
        # 加载所有用户信息
        try:
            with open(self.path, 'r', encoding='utf-8') as file:
                self.users = json.load(file)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f'Error loading user data: {e}')

    def generate_captcha(self):
        # 生成验证码
        digits = "0123456789"
        captcha = ''.join(random.choices(digits, k=4))
        return captcha

    def reset_password(self):
        """ 重置密码 """
        username = str(input("输入你的账号："))
        while True:
            captcha = self.generate_captcha()
            print("验证码：", captcha)
            input_captcha = str(input("请输入验证码："))
            if input_captcha == captcha:
                # 先校验输入的账号是否存在
                user = self.find_user_by_username(username)
                if user is None:
                    print("账号不存在！")
                    return False
                else:
                    time.sleep(2)
                    print("【重置密码】：")
                    new_password = str(input("\t请输入新密码："))
                    new_password = hashlib.sha256(new_password.encode()).hexdigest()
                    self.update_password(user, new_password)
                    print("重置成功！")
                    break
            else:
                print("验证码错误，请重新输入！")

    def find_user_by_username(self, username):
        # 根据账号查找用户
        for user in self.users:
            if user['username'] == username:
                return user
                # user_password = hashlib.sha256(user['password'].encode()).hexdigest()
                # return user_password
        return None

    def update_password(self, user, new_password):
        # 更新密码
        user['password'] = new_password
        self.save_users()

    def save_users(self):
        try:
            with open(self.path, 'w') as file:
                json.dump(self.users, file, indent=4)
        except FileNotFoundError as e:
            print(f'Error saving user data: {e}')
# f = ForgetPassword()
# f.reset_password()
